package standino.velocity.db.db2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import standino.velocity.text.RegexTool;

public class TableBuilder {
	private Table table;

	private List<SP> sps = new ArrayList<SP>(8);



	public void build(String fileName) {
		try {
			BufferedReader in = new BufferedReader(new FileReader(fileName));
			String str;
			while ((str = in.readLine()) != null) {
				process(str);
			}
			fillSPsPara();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void process(String str) {
		this.tableMatch(RegexTool.removeDuplicateWhitespace(str));


	}

	private void tableMatch(String str) {

		Matcher matcher = match(str, "<table>");
		boolean matchFound = matcher.find(); // false
		if (matchFound) {
			String tabName = matcher.replaceAll("").trim();
			this.table = new Table(tabName);
		} else {
			spMatch(str);
		}

	}

	private Matcher match(String str, String patternStr) {
		// Compile regular expression
		// String patternStr = "<table>";
		Pattern pattern = Pattern.compile(patternStr);

		Matcher matcher = pattern.matcher(str);
		return matcher;
	}

	private void spMatch(String str) {
		Matcher matcher = match(str, "<.{1,2}SP>");
		boolean matchFound = matcher.find(); // false
		if (matchFound) {
			String type = matcher.group();
			type = type.replace("<", "").replace(">", "");
			String spName = matcher.replaceAll("").trim();
			SP sp = new SP(spName);
			sp.addRefTableName(this.table.getFullName());
			sp.setType(type);
			this.sps.add(sp);
		} else {
			colMatch(str);
		}

	}

	private void colMatch(String str) {
		Column col = new Column();
		str = str.toUpperCase();
		Matcher matcher = match(str, "NOT NULL");
		if (matcher.find()) {
			col.setAllowNull(false);
			str = matcher.replaceAll("").trim();
		} else {
			col.setAllowNull(true);
		}


		matcher = match(str, "PK");
		if (matcher.find()) {
			col.setPk(true);
			str = matcher.replaceAll("").trim();
		}

		StringTokenizer st = new StringTokenizer(str);

		if (st.hasMoreTokens()) {
			col.setName(st.nextToken());
		}
		if (st.hasMoreTokens()) {
			col.setType(st.nextToken());
		}

		this.table.addColumns(col);
	}

	private void fillSPsPara(){

		for(Column co:this.table.getColumns()){
			Parameter pa = new Parameter(co);
			for(SP sp:this.sps){
				sp.addInParam(pa);
			}
		}

	}

	public List<SP> getSps() {
		return sps;
	}

	public void setSps(List<SP> sps) {
		this.sps = sps;
	}

	public Table getTable() {
		return table;
	}

	public void setTable(Table table) {
		this.table = table;
	}
}
